package com.api.gateway.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;

/**
 * AES加解密
 */
public class AESUtils {
    public static String getRandomKey(){
        try {
            KeyGenerator kg = KeyGenerator.getInstance("AES");
            kg.init(128);
            SecretKey sk = kg.generateKey();
            byte[] b = sk.getEncoded();
            return ByteUtils.byteToHex(b);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String encrypt(String str, String hexKey) {
        try{
            SecretKeySpec sks = new SecretKeySpec(ByteUtils.hexToByte(hexKey), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, sks);
            byte[] eb = cipher.doFinal(str.getBytes("utf-8"));
            return new BASE64Encoder().encode(eb).replaceAll("\n", "");
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String str, String hexKey) {
        try{
            SecretKeySpec sks = new SecretKeySpec(ByteUtils.hexToByte(hexKey), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, sks);
            byte[] by = new BASE64Decoder().decodeBuffer(str);
            byte[] db = cipher.doFinal(by);
            return new String(db);
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
}